import 'package:flutter/material.dart';
import 'package:top_foundation/utils/util.dart';

import '../../utils/popup/index.dart';

class DropBtn extends StatefulWidget {
  const DropBtn({
    super.key,
    required this.titles,
    this.initIndex = 0,
    this.color,
    this.fontSize,
    this.popWidth,
    this.prefixList,
    this.height,
    this.width,
    required this.onChanged,
  });
  final List<String> titles;
  final int initIndex;
  final Color? color;
  final double? fontSize;
  final double? popWidth;
  final double? height;
  final double? width;
  final List<Widget>? prefixList;
  final ValueChanged<int> onChanged;
  @override
  State<DropBtn> createState() => _DropBtnState();
}

class _DropBtnState extends State<DropBtn> {
  late final GlobalKey key = GlobalKey();
  int curr = 0;

  String get title {
    return widget.titles[curr];
  }

  @override
  void initState() {
    curr = widget.initIndex;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: SizedBox(
        key: key,
        height: widget.height,
        width: widget.width,
        child: Row(
          children: [
            Text(
              title,
              style: TextStyle(
                  color: widget.color ?? const Color(0xff333333),
                  fontSize: widget.fontSize ?? 15.sp),
            ),
            const SizedBox(width: 5),
            Icon(
              Icons.keyboard_arrow_down_sharp,
              color: widget.color ?? const Color(0xff333333),
              size: 20.r,
            ),
          ],
        ),
      ),
    );
  }

  void onTap() async {
    final res = await Popup.dropDown(
      data: widget.titles,
      initValue: widget.titles[curr],
      sourceKey: key,
      prefixList: widget.prefixList,
      width: widget.popWidth,
    );
    if (res != null) {
      curr = res;
      setState(() {});
      widget.onChanged(curr);
    }
  }
}
